package com.example.auth.service;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.auth.util.BCryptUtils;
import com.example.common.dao.user.UserMapper;
import com.example.common.dto.base.ResultMsg;
import com.example.common.dto.user.LoginReqDto;
import com.example.common.dto.user.UserDto;
import com.example.common.entity.user.UserEntity;
import com.example.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author huangjie
 */
@Slf4j
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserService extends ServiceImpl<UserMapper, UserEntity> {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public ResultMsg<String> login(LoginReqDto loginReqDto) {
        UserEntity userEntity = this.getOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getPhone,loginReqDto.getPhone()),false);
        Assert.notNull(userEntity, "账号不存在：" + loginReqDto.getPhone());
        Assert.hasLength(userEntity.getPassword(),"账号未设置密码，请先设置密码");
        // 2. 验证密码（BCrypt 自动处理盐和匹配）
        boolean matches = BCryptUtils.matches(loginReqDto.getPassword(), userEntity.getPassword());
        Assert.isTrue(matches,"密码错误");


        // 生成 JWT
        String token = JwtUtil.generateToken(userEntity.getId(), userEntity.getPhone());
        redisTemplate.opsForValue().set("USERID:" + userEntity.getId(), token, 60, TimeUnit.MINUTES);
        return ResultMsg.generateSuccessResults("登陆成功", token);
    }

    public ResultMsg<String> register(UserDto userDto) {
         String encodeedPassword = BCryptUtils.encode(userDto.getPassword());
         UserEntity userEntity = new UserEntity();
         userEntity.setName(userDto.getName());
         userEntity.setPassword(encodeedPassword);
         userEntity.setPhone(userDto.getPhone());
         this.save(userEntity);
         return ResultMsg.generateSuccessResults("注册成功");
    }

    public void logout(String userId) {
        redisTemplate.delete("USERID:" + userId);
    }
}
